//
//  ViewController.swift
//  测试-图片查看器
//
//  Created by shmily on 15/8/9.
//  Copyright © 2015年 shmilyAshen. All rights reserved.
//

import UIKit
import SVProgressHUD

private let kPictureBroswerCellID = "kPictureBroswerCellID"

class PictureBroswerVC: UIViewController {

    /// 数据源
    private var imgUrls: [NSURL]?
    private var index: Int = 0
    
    //MARK:- 按钮单击事件
    func saveImage() {
        let indexPath = collecitonView.indexPathsForVisibleItems().last!
        let cell = collecitonView.cellForItemAtIndexPath(indexPath) as! PictureBroswerCell
        guard let img = cell.imgView.image else {
            return
        }
         UIImageWriteToSavedPhotosAlbum(img, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    //保存图像调用此方法,方法名唯一,不允许修改
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?){
        let info = (error != nil) ? "保存失败" : "保存成功"
        SVProgressHUD.showInfoWithStatus(info)
    }
    
    func closeVC() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK:- 初始化构造函数
    init(urls: [NSURL],index: Int) {
        super.init(nibName: nil, bundle: nil)
        
        imgUrls = urls // 获取数据源
        self.index = index
    }

    override func loadView() {
        super.loadView()
        
        // 增大 view 的宽度,以使图像之间存在间隔
        var frame = UIScreen.mainScreen().bounds
        frame.size.width += 20
        view = UIView(frame: frame)
        
        setupUI()
        setupCollectionView()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        collecitonView.scrollToItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    /// 设置显示 UI
    private func setupUI() {
        view.addSubview(collecitonView)
        view.addSubview(btnClose)
        view.addSubview(btnSave)
        
        //设置布局
        //按钮的布局
        //let array = ["save":btnSave,"close": btnClose]
        let w = 100
        let h = 32
        let x = 8
        let y = Int(UIScreen.mainScreen().bounds.height) - 8 - h
        btnClose.frame = CGRect(x: x, y: y, width: w, height: h)
        btnSave.frame = CGRect(x: Int(UIScreen.mainScreen().bounds.width) - x - w, y: y, width: w, height: h)

        //collectionView 的布局
        collecitonView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv":collecitonView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv":collecitonView]))
    }
    
    /// 设置 collecitonView 属性
    private func setupCollectionView() {
        collecitonView.registerClass(PictureBroswerCell.self, forCellWithReuseIdentifier: kPictureBroswerCellID)
        collecitonView.dataSource = self
        
        let flowLayout = collecitonView.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        flowLayout.itemSize = view.bounds.size
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
        collecitonView.pagingEnabled = true
        collecitonView.showsHorizontalScrollIndicator = false // 改为 false
    }
    
    //MARK:- 懒加载视图和数据源
    /// 关闭按钮
    private lazy var btnClose: UIButton = {
        let btn = UIButton()
        btn.setTitle("关闭", forState: UIControlState.Normal)
        btn.addTarget(self, action: "closeVC", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    /// 保存按钮
    private lazy var btnSave: UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", forState: UIControlState.Normal)
        btn.addTarget(self, action: "saveImage", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()

    //collectionView 视图
    private lazy var collecitonView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
}

// MARK: - collectionView 的数据源方法
extension PictureBroswerVC: UICollectionViewDataSource {
    // cell 的数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgUrls?.count ?? 0
    }
    //cell 的内容
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collecitonView.dequeueReusableCellWithReuseIdentifier(kPictureBroswerCellID, forIndexPath: indexPath) as! PictureBroswerCell
        // 设置数据
        cell.imageUrl = imgUrls![indexPath.item]
        return cell
    }
}
